package com.lazy.gridfs;

import java.nio.charset.StandardCharsets;
import java.util.Date;

import com.lazy.lib.util.DateUtil;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSUploadStream;

public class GridFsUtil {
    
    
    public void test(MongoDatabase database, byte[] binData) {
        GridFSBucket gridFSBucket = GridFSBuckets.create(database);
        
        long time = System.currentTimeMillis();
        String fileName = DateUtil.formatDate(new Date(time), "yyyyMMddHHmmss");
        GridFSUploadStream uploadStream = null;
        try {
            gridFSBucket.openUploadStream(fileName);
            uploadStream.write(binData);
        } finally {
            if (uploadStream != null) {
                uploadStream.close();
            }
        }
    }
    
    public void testMulti2() {
        //String host = "192.168.1.234";
        //int port = 27027;
        String host = "192.168.1.178";
        int port = 27017;
        MongoClient mongoClient =  new MongoClient(host, port);
        // get handle to "mydb" database
        MongoDatabase database = mongoClient.getDatabase("mydb");
        database.drop();

        GridFSBucket gridFSBucket = GridFSBuckets.create(database);
        
        //long start = System.currentTimeMillis();
        /*
         * UploadFromStream Example
         */
        String data = "database mydb on connection [connectionId{localValue :2, serverValue:57}] to server 127.0.0.1:27017 ";
        StringBuilder sb = new StringBuilder();
        // 100 bytes * 10000 = 1M
        for (int i = 0; i < 10000; i++) {
            sb.append(data);
        }
        long start = System.currentTimeMillis();
        byte[] binData = sb.toString().getBytes(StandardCharsets.UTF_8);
        
        // Create some custom options
        //GridFSUploadOptions options = new GridFSUploadOptions()
        //        .chunkSizeBytes(1024000)
        //        .metadata(new Document("type", "presentation"));
        for (int j = 0; j < 1000; j++) {
            GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("mongodb-tutorial" + j);
            uploadStream.write(binData);
            uploadStream.close();
        }
        //System.out.println("The fileId of the uploaded file is: " + fileId.toHexString());
        System.out.println("took times " + (System.currentTimeMillis() - start));
    }
}
